package com.party.mobile.biz.order.payOrder;

import com.party.core.model.order.OrderForm;
import com.party.core.model.order.OrderType;
import com.party.mobile.biz.order.OrderBizService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by wei.li
 * on 2019/4/17
 */
@Service
public abstract class IPayOrderService {
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private OrderBizService orderBizService;

    private ExecutorService threadPool = Executors.newFixedThreadPool(50);



    /**
     * 订单支付
     *
     * @param orderForm  订单信息
     * @param object     支付数据
     * @param paymentWay 支付类型
     */
    protected Object payOrder(OrderForm orderForm, Object object, Integer paymentWay) {
        // 订单持久化 交易流水
        orderBizService.updateOrderStatus(orderForm, object, paymentWay);

        // 主业务处理
        return doMain(orderForm);
    }


    /**
     * 支付业务
     *
     * @param orderForm
     * @param object
     * @param paymentWay
     */
    public void doPay(OrderForm orderForm, Object object, Integer paymentWay) {
        Object resultObject = null;
        try {
            long start = System.currentTimeMillis();
            resultObject = this.payOrder(orderForm, object, paymentWay);
            long end = System.currentTimeMillis();
            logger.info("payOrder----订单类型：{}，订单id：{}，执行时间：{}(ms)", OrderType.getValue(orderForm.getType()), orderForm.getId(), (end - start));
        } catch (Exception e) {
            logger.info("支付回调同步方法异常", e);
            throw e;
        }

        //处理异步事件
        Object finalResultObject = resultObject;
        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                long start = System.currentTimeMillis();
                doAssist(orderForm, finalResultObject);
                long end = System.currentTimeMillis();
                logger.info("doAssist----订单类型：{}，订单id：{}，执行时间：{}(ms)", OrderType.getValue(orderForm.getType()), orderForm.getId(), (end - start));
            }
        });
    }


    /**
     * 处理支付主业务，需要事务控制
     *
     * @param orderForm
     */
    protected abstract Object doMain(OrderForm orderForm);


    /**
     * 处理附属业务，异步处理
     *
     * @param orderForm
     */
    protected abstract void doAssist(OrderForm orderForm, Object resultObject);
}
